<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2019/08/09 11:35
 * Desc: 户外活动
 */
class Model_Api_Standard_Outdoor
{

    private static $basefiled = 'a.color,a.finaldestid,a.team_number,a.id,a.webid,a.aid,a.lineday,a.title,a.price,a.price_date,a.litpic,a.startcity,a.kindlist,a.attrid,a.bookcount,a.storeprice,a.sellpoint,a.iconlist,a.satisfyscore,a.number,a.bookstarttime,a.bookendtime,a.starttime';
    private static $_typeid = 114;

    /**
     * @function 户外活动属性
     * @param $params
     * @return array
     */
    public static function attr($params)
    {
        $default = array(
            'pid' => 0,
            'row' => 10,
            'offset' => 0
        );
        $params = array_merge($default, $params);
        extract($params);
        $w = " where isopen=1 and pid='{$pid}' ";

        $sql = "select * from sline_outdoor_attr $w order by ifnull(displayorder,9999) asc,id asc limit {$offset},{$row}";
        $sql_num = "select count(*) as num from sline_outdoor_attr $w";

        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $num = DB::query(Database::SELECT, $sql_num)->execute()->get('num');

        return array('list' => $list, 'total_count' => $num);
    }

    /**
     * 读取最新活动
     * @function
     * @param $offset
     * @param $row
     * @param $bookstatus
     * @param $startcityid
     * @param int $supplier_id
     * @return mixed
     */
    public static function get_outdoor_new($offset, $row, $bookstatus, $startcityid,$supplier_id = 0)
    {

        $offset = intval($offset);
        $row = intval($row);

        $w = "WHERE a.ishidden=0 AND  a.webid=0 and a.status=3 ";

        if($supplier_id)
        {
            $w .= " AND a.supplierlist='$supplier_id'";
        }

        if (!empty($startcityid))
        {
            $w .= " and a.startcity='{$startcityid}'";
        }


        $sql = "SELECT " . self::$basefiled . " FROM `sline_outdoor` AS a LEFT JOIN `sline_allorderlist` b ON (a.id=b.aid and b.typeid=" . self::$_typeid . ") ";
        $sql .= " {$w} ORDER BY a.modtime DESC,a.addtime DESC,IFNULL(b.displayorder,9999) ASC ";
        $sql .= "LIMIT {$offset},{$row}";
        $arr = DB::query(Database::SELECT, $sql)->execute()->as_array();
        return $arr;
    }

    //读取全局户外活动
    public static function get_outdoor_order($offset, $row, $bookstatus, $startcityid,$supplier_id = 0)
    {

        $offset = intval($offset);
        $row = intval($row);

        $w = "WHERE a.ishidden=0 AND  a.webid=0 and a.status=3 ";
        if($supplier_id)
        {
            $w .= " AND a.supplierlist='$supplier_id'";
        }
        if (!empty($startcityid))
        {
            $w .= " and a.startcity='{$startcityid}'";
        }
        $sql = "SELECT " . self::$basefiled . " FROM `sline_outdoor` AS a LEFT JOIN `sline_allorderlist` b ON (a.id=b.aid and b.typeid=" . self::$_typeid . ") ";
        $sql .= " {$w} ORDER BY IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";
        $sql .= "LIMIT {$offset},{$row}";
        $arr = DB::query(Database::SELECT, $sql)->execute()->as_array();
        return $arr;
    }


    /**
     * 参数解析
     * @param $params
     */
    public static function search_result($params)
    {
        $destPy = $params['destpy'];
        $dayId = intval($params['dayid']);
        $priceId = intval($params['priceid']);
        $sortType = intval($params['sorttype']);
        $startcityId = intval($params['startcityid']);
        $attrId = $params['attrid'];
        $keyword = strip_tags($params['keyword']);
        $keyword = St_String::filter_mark($keyword);

        $dest_keyword = strip_tags($params['dest_keyword']);
        $dest_keyword = St_String::filter_mark($dest_keyword);

        $groupid = intval($params['groupid']);
        $page = intval($params['page']);;
        $page = $page ? $page : 1;
        $pagesize = intval($params['pagesize']);
        $pagesize = $pagesize ? $pagesize : 10;

        $value_arr = array();
        $where = " WHERE a.ishidden=0 and a.status=3 ";
        //按目的地搜索
        if ($destPy && $destPy != 'all')
        {
            $destId = DB::select('id')->from('destinations')->where('pinyin', '=', $destPy)->execute()->get('id');
            $where .= " AND FIND_IN_SET('$destId',a.kindlist) ";
        }
        //天数
        if ($dayId)
        {

            if (Model_Outdoor::is_last_day($dayId))
            {
                $where .= " AND a.lineday>='$dayId'";
            }
            else
            {
                $where .= " AND a.lineday='$dayId'";
            }

        }

        if(!empty($dest_keyword))
        {
            $dest_id = DB::select('id')->from('destinations')->where('kindname', '=', $dest_keyword)->execute()->get('id');
            if(!empty($dest_id))
            {
                $where.=" AND (a.title like '%{$dest_keyword}%' or find_in_set({$dest_id},a.kindlist)) ";
            }
            else
            {
                $where.=" and a.title like '%{$dest_keyword}%' ";
            }
        }

        //价格区间
        if ($priceId)
        {

            $priceArr = DB::select()->from('outdoor_pricelist')->where('id', '=', $priceId)->execute()->current();
            $where .= " AND a.price BETWEEN {$priceArr['lowerprice']} AND {$priceArr['highprice']} ";
        }


        //圈子
        if ($groupid)
        {
            $where .= " AND a.groupid={$groupid} ";
        }


        $curtime = time();
        //排序
        $orderBy = "";
        if (!empty($sortType))
        {
            if ($sortType == 1)//价格升序
            {
                $orderBy = "  a.price ASC,";
            }
            else if ($sortType == 2) //价格降序
            {
                $orderBy = "  a.price DESC,";
            }
            else if ($sortType == 3) //销量降序
            {
                $orderBy = " sellnum DESC,";
            }
            else if ($sortType == 4)//推荐
            {
                $orderBy = " a.shownum DESC,";
            }
            /*  else if($sortType==5) //满意度
              {
                  $orderBy = " a.shownum desc,";
              }*/
            //根据出发时间倒序
            else if ($sortType == 6)
            {
                $orderBy = " a.starttime DESC,";
            }
            else if ($sortType == 7)
            {
                $orderBy = " a.starttime ASC,";
            }
        }

        //关键词
        if (!empty($startcityId))
        {
            $where .= " AND a.startcity=$startcityId ";
        }
        //按属性
        if (!empty($attrId))
        {
            $where .= Product::get_attr_where($attrId);
        }
        //按关键词
        if (!empty($keyword))
        {
            $value_arr[':keyword'] = '%' . $keyword . '%';
            $where .= " AND a.title like :keyword ";
        }

        $offset = (intval($page) - 1) * $pagesize;

        $orderBy = empty($orderBy) ? " IFNULL(b.displayorder,9999) ASC,a.bookendtime desc, " : $orderBy;
        //查询真实购买量
        $sell_where = " LEFT JOIN (SELECT COUNT(*) as s_num,productautoid FROM `sline_member_order` WHERE typeid=".self::$_typeid." GROUP BY productautoid) AS s ON s.productautoid=a.id";
        $files = ",(IFNULL(a.bookcount,0)+IFNULL(s.s_num,0)) AS sellnum";
        //如果选择了目的地
        if (!empty($destId))
        {
            $sql = "SELECT a.*{$files} FROM `sline_outdoor` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=" . self::$_typeid . " AND a.webid=b.webid AND b.classid=$destId)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";

        }
        else
        {
            $sql = "SELECT a.*{$files} FROM `sline_outdoor` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=" . self::$_typeid . " AND a.webid=b.webid)";
            $sql .= $sell_where;
            $sql .= $where;
            //$sql.= "ORDER BY IFNULL(b.displayorder,9999) ASC,{$orderBy}a.modtime DESC,a.addtime DESC ";
            $sql .= "ORDER BY {$orderBy} a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";

        }

        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by


        $totalN = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        //数据量大时的优化方法,数据量小时不推荐使用此方法
        //$idWhere = "SELECT id FROM `sline_line` ORDER BY id limit $offset, 1";
        //$sql = str_replace("WHERE","WHERE a.id>($idWhere) AND",$sql);
        //$sql.= "LIMIT {$pagesize}";

        $sql .= "LIMIT {$offset},{$pagesize}";

        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();
        foreach ($arr as &$v)
        {
            $v['price'] = Model_Outdoor::get_minprice($v['id'], array('info' => $v));
            $v['price'] = floatval($v['price']);
            $v['attrlist'] = Model_Outdoor::line_attr($v['attrid']);
            $v['startcity_name'] = Model_Startplace::start_city($v['startcity']);
            $v['finaldest_name'] = DB::select('kindname')->from('destinations')->where('id', '=', $v['finaldestid'])->execute()->get('kindname');
            $v['group_name'] = DB::select('title')->from('outdoor_group')->where('id', '=', $v['groupid'])->execute()->get('title');
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], self::$_typeid); //评论次数
            //$v['sellnum'] = Model_Member_Order::get_sell_num($v['id'], self::$_typeid) + intval($v['bookcount']); //销售数量
            $v['url'] = Common::get_web_url($v['webid']) . "/outdoor/show_{$v['aid']}.html";
            $v['litpic'] = Common::img($v['litpic']);
            $v['iconlist'] = Product::get_ico_list($v['iconlist']);
            $v['cfg_icon_rule']  = $GLOBALS['cfg_icon_rule'];
            $v['score'] = St_Functions::get_satisfy(self::$_typeid, $v['id'], $v['satisfyscore']);
            $v['jifentprice_info'] = Model_Jifen_Price::get_used_jifentprice($v['jifentprice_id'],self::$_typeid);
            $v['startDay']= isset($v['price_date']) ? date("m月d",$v['price_date']): '';
//            $v['joined_number'] = self::get_joined_number($v['id']);
//             $v['bookstatus'] = Model_Outdoor::get_book_status($v['bookstarttime'], $v['bookendtime']);
//            $v['bookstatus']= Model_Outdoor::get_book_status($v);
//             $v['bookstatus_name'] = Model_Outdoor::get_bookstatus_name($v['bookstatus']);
            $v['periods'] = Model_Outdoor::get_bookable_periods($v['id'],1);
            $v['bookstatus_name'] = isset($v['periods'][0]['bookstatus_name']) ? $v['periods'][0]['bookstatus_name'] : '';
            if(Model_Supplier::display_is_open()&&$v['supplierlist'])
            {
                $v['suppliername'] = Arr::get(Model_Supplier::get_supplier_info($v['supplierlist'],array('suppliername')),'suppliername');
            }
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr
        );
        return $out;

    }

    /**
     * 获取活动行程
     * @function
     * @param $params
     * @return array
     */
    public static function get_detail_content($params)
    {
        $default = array(
            'typeid' => '114',
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );

        $params = array_merge($default, $params);
        extract($params);
        $arr = DB::select()->from('outdoor_content')
            ->and_where('isopen','=',1)
            ->order_by('displayorder','ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar = DB::select()->from('outdoor_extend_field')->where('productid','=',$productid)->execute()->as_array();

        $list = array();
        foreach ($arr as $v)
        {
            if ($v['columnname'] == 'tupian' || $v['columnname'] == 'linedoc')
            {
                continue;
            }
            if ($v['isrealfield'] == 1 && $v['columnname'] != 'content')
            {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
                if (empty($content))
                {
                    continue;
                }
            }


            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            if ($v['columnname'] == 'content' && $productinfo['isstyle'] == 1)
            {
                $detail = Model_Outdoor_Jieshao::detail($productinfo['id'],$productinfo['lineday']);
                foreach($detail as &$d)
                {
                    $d['jieshao'] = Model_Api_Standard_Xcx::filter_content($d['content']);
                }

                $a['content'] = $detail;
                $a['is_array'] = 1;
            }
            else if($v['columnname'] == 'content' && $productinfo['isstyle'] == 0)
            {
                $content = $productinfo['content'];
                if(empty($content))
                {
                    continue;
                }
                $a['is_array'] = 0;
                $a['content']  = Model_Api_Standard_Xcx::filter_content($content);

            }
            else
            {
                $a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            }

            //$a['xcx_content'] = Model_Api_Standard_Xcx::filter_content($content); //针对小程序去除样式
            //$a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            $list[] = $a;

        }

        return $list;
    }

    /**
     * 获取订单详情
     * @function
     * @param $id
     * @param $mid
     * @return array
     */
    public static function get_order_detail($id,$mid)
    {
        $orderSn = DB::select('ordersn')->from("member_order")->where("id",'=',$id)->and_where("typeid","=",self::$_typeid)->execute()->get('ordersn');
        $info = Model_Member_Order::order_info($orderSn,$mid);
        $status=DB::select()->from('outdoor_order_status')->where('status','=',$info['status'])->and_where('is_show','=',1)->execute()->current();
        $info['statusname'] = $status['status_name'];
        $info = Pay_Online_Refund::get_refund_info($info);
        // 初始化数据
        $info['add_time'] = date("Y-m-d",$info['addtime']);
        $info['litpic']   = Common::img($info['litpic']);
        $info["web_url"]  =  $GLOBALS['cfg_basehost'];

        $tourer_fields = Model_Outdoor_Tourer_Desc::get_tourer_fields($info['productautoid']);
        $tourers = DB::select()->from('outdoor_tourer')->where('orderid','=',$info['id'])->execute()->as_array();
        $product = St_Product::get_product_info($info['typeid'],$info['productautoid']);
        $product['finaldest_name'] = DB::select('kindname')->from('destinations')->where('id', '=', $product['finaldestid'])->execute()->get('kindname');
        $product['startcity_name'] = Model_Startplace::start_city($product['startcity']);

        $suit = DB::select()->from('outdoor_suit')->where('id','=',$info['suitid'])->execute()->current();

        $result = array(
            'info'=> $info,
            'tourer_fields'=> $tourer_fields,
            'tourers'=> $tourers,
            'product'=> $product,
            'suit'=> $suit,
        );

        return $result;
    }


    /**
     * @function 获取已预订的会员信息
     * @param $outdoorid
     * @param $page
     * @param $pagesize
     * @param $params
     */
    public static function search_order_members($outdoorid, $page = -1, $pagesize = 10, $params = null)
    {

        $page = intval($page);
        $page = $page == 0 ? 1 : $page;
        $offset = $pagesize * ($page - 1);

        $fields = "linkman,linktel,memberid,addtime,dingnum,remark";
        $w = "WHERE typeid=" . self::$_typeid . " AND productautoid={$outdoorid} AND status IN (2,5)";
        $sql = " SELECT {$fields} FROM sline_member_order ";
        $sql .= $w;
        $sql .= " ORDER BY addtime DESC";
        if ($page != -1)
        {
            $sql .= "LIMIT {$offset},{$pagesize}";
        }
        $sql_num = "SELECT COUNT(*) AS num from sline_member_order {$w}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $total = DB::query(Database::SELECT, $sql_num)->execute()->get('num');
        foreach ($list as &$v)
        {
            $member_info = DB::select('nickname', 'mobile', 'litpic')->from('member')->where('mid', '=', $v['memberid'])->execute()->current();
            $v['nickname'] = empty($member_info['nickname']) ? '匿名' : $member_info['nickname'];
            $v['linkman'] = self::format_name($v['linkman']);
            $v['linktel'] = self::format_mobile($v['linktel']);
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $v['litpic'] = empty($member_info['litpic']) ? "/res/images/member_nopic.png" : $member_info['litpic'];
            unset($v['memberid']);
        }
        return array('total' => $total, 'page' => $page, 'pagesize' => $pagesize, 'list' => $list);
    }


    /**
     * @function 格式化用户名
     * @param $name
     * @return string
     */
    public static function format_name($name)
    {
        if (empty($name))
        {
            return '';
        }
        $first = mb_substr($name, 0, 1, 'UTF-8');
        $other = mb_substr($name, 1, mb_strlen($name, 'UTF-8'), 'UTF-8');
        $len = mb_strlen($other, 'UTF-8');
        $str = $first;
        while ($len > 0)
        {
            $str .= '*';
            $len--;
        }
        return $str;
    }

    /**
     * @function 格式化电话
     * @param $phone
     * @return string
     */
    public static function format_mobile($phone)
    {
        if (empty($phone))
        {
            return '';
        }
        $first = substr($phone, 0, 3);
        $last = substr($phone, -4, 4);
        return $first . '***' . $last;
    }

}